using System;
using System.Threading.Tasks;
using BanZuiCloudControlAgent.Extensions.QQ;
using BanZuiCloudControlAgent.Utils.Logging;
using Newtonsoft.Json;
using RestSharp;

namespace BanZuiCloudControlAgent.Core.QQ
{
    /// <summary>
    /// QQ 群组 Web 相关操作
    /// </summary>
    public class QQGroupWeb
    {
        private readonly string _cookie;
        private readonly RestClient _client;
        private static readonly Logger _logger = LogManager.GetLogger(nameof(QQGroupWeb));

        public QQGroupWeb(string cookie)
        {
            _cookie = cookie ?? throw new ArgumentNullException(nameof(cookie));
            _client = new RestClient("https://qun.qq.com");
        }

        /// <summary>
        /// 从QQ进程直接获取并初始化QQGroupWeb
        /// </summary>
        /// <param name="processId">QQ进程ID</param>
        /// <returns>QQGroupWeb实例，如果无法获取Cookie则返回null</returns>
        public static QQGroupWeb CreateFromProcessAsync(int processId)
        {
            // 获取QQ号
            string qqNumber = null;
            var qqManager = QQManager.GetInstance();
            var qq = qqManager.GetQQ(processId);
            if (qq != null && qq.IsOnline)
            {
                qqNumber = qq.QQNumber;
            }

            if (string.IsNullOrEmpty(qqNumber))
            {
                qqNumber = QQWrapper.GetQQNumber(processId);
                if (string.IsNullOrEmpty(qqNumber))
                {
                    _logger.Error($"[CreateFromProcessAsync] 无法获取进程ID为 {processId} 的QQ号");
                    return null;
                }
            }

            // 获取Cookie
            string cookie = QQExtension.GetCookie(qqNumber, processId);
            if (string.IsNullOrEmpty(cookie))
            {
                _logger.Error($"[CreateFromProcessAsync] 无法获取QQ {qqNumber} 的Cookie");
                return null;
            }

            return new QQGroupWeb(cookie);
        }

        public async Task GetGroupModelByWeb()
        {
            // 从cookie中获取skey
            string skey = QQExtension.GetValueFromCookie(_cookie, "skey");
            _logger.Info($"[GetGroupModelByWeb] skey:{skey}");
            if (string.IsNullOrEmpty(skey))
            {
                _logger.Error("[GetGroupModelByWeb] Error: No skey found in cookie");
                return;
            }
            string bkn = QQExtension.GetGtkBySkey(skey);
            _logger.Info($"[GetGroupModelByWeb] bkn:{bkn}");
            if (string.IsNullOrEmpty(bkn))
            {
                _logger.Error("[GetGroupModelByWeb] Error: No bkn found");
                return;
            }

            var request = new RestRequest("/cgi-bin/qun_mgr/get_group_list", Method.Post);

            request.Timeout = TimeSpan.FromMilliseconds(10000);
            request.AddHeader("Accept", "application/json, text/plain, */*");
            request.AddHeader("Cookie", _cookie);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("bkn", bkn);
            var response = await _client.ExecuteAsync(request);
            _logger.Info($"[GetGroupModelByWeb] response:{response.Content}");
            if (response.IsSuccessful)
            {
                _logger.Info($"[GetGroupModelByWeb] Response:{response.Content}");
                // 获取json数据
                var json = response.Content;
                if (string.IsNullOrEmpty(json))
                {
                    _logger.Error("Error: No data received");
                    return;
                }

                // 使用 GroupModel 类解析 JSON 数据
                GroupWebModel groupModel = JsonConvert.DeserializeObject<GroupWebModel>(json);
                if (groupModel == null)
                {
                    _logger.Error("[GetGroupModelByWeb] Error: Failed to parse json data");
                    return;
                }

                // 输出 join 和 manage 数据
                _logger.Info("Join Groups:");
                foreach (var group in groupModel.Join)
                {
                    _logger.Info($"[GetGroupModelByWeb] Group Code: {group.GroupNumber}, Name: {group.GroupName}, Owner: {group.Owner}");
                }

                _logger.Info("Manage Groups:");
                foreach (var group in groupModel.Manage)
                {
                    _logger.Info($"[GetGroupModelByWeb] Group Code: {group.GroupNumber}, Name: {group.GroupName}, Owner: {group.Owner}");
                }
            }
            else
            {
                _logger.Error($"[GetGroupModelByWeb] Error: StatusCode:{response.StatusCode}");
            }
        }

        /// <summary>
        /// 获取群组模型
        /// </summary>
        /// <returns>群组模型</returns>
        public async Task<GroupWebModel> GetGroupModelAsync()
        {
            string skey = QQExtension.GetValueFromCookie(_cookie, "skey");
            if (string.IsNullOrEmpty(skey))
            {
                _logger.Error("[GetGroupModelAsync] Error: No skey found in cookie");
                throw new InvalidOperationException("Cookie 中缺少 skey");
            }

            string bkn = QQExtension.GetGtkBySkey(skey);

            var request = new RestRequest("/cgi-bin/qun_mgr/get_group_list", Method.Post)
            {
                Timeout = TimeSpan.FromMilliseconds(10000)
            };
            request.AddHeader("Accept", "application/json, text/plain, */*");
            request.AddHeader("Cookie", _cookie);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("bkn", bkn);

            var response = await _client.ExecuteAsync(request);
            if (!response.IsSuccessful || string.IsNullOrEmpty(response.Content))
            {
                _logger.Error($"[GetGroupModelAsync] Error: {response.StatusCode}, {response.ErrorMessage}");
                throw new InvalidOperationException("获取群组数据失败");
            }
            _logger.Info($"[GetGroupModelAsync] Response:{response.Content}");
            GroupWebModel groupModel = JsonConvert.DeserializeObject<GroupWebModel>(response.Content);
            if (groupModel == null)
            {
                _logger.Error("[GetGroupModelAsync] Error: Failed to parse JSON data");
                throw new InvalidOperationException("解析群组数据失败");
            }
            return groupModel;
        }
    }

    /// <summary>
    /// 群组Web模型
    /// </summary>
    public class GroupWebModel
    {
        [JsonProperty("join")]
        public GroupInfo[] Join { get; set; }

        [JsonProperty("manage")]
        public GroupInfo[] Manage { get; set; }

        [JsonProperty("create")]
        public GroupInfo[] Create { get; set; }
    }

    /// <summary>
    /// 群信息
    /// </summary>
    public class GroupInfo
    {
        [JsonProperty("gc")]
        public long GroupNumber { get; set; }

        [JsonProperty("gn")]
        public string GroupName { get; set; }

        [JsonProperty("owner")]
        public long Owner { get; set; }

        [JsonProperty("count")]
        public int MemberCount { get; set; }

        [JsonProperty("max_count")]
        public int MaxMemberCount { get; set; }
    }
}